package com.whfc.iot.mach.event;

import com.google.common.cache.LoadingCache;
import com.whfc.common.util.JSONUtil;
import com.whfc.hdc.dto.AppDeviceParamDTO;
import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.*;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 设备上线事件后 - 参数设置监听器
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/8/23 14:49
 */
@Component
public class DeviceOnlineEventParamSetListener implements ApplicationListener<DeviceOnlineEvent> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SessionManager sessionManager;

    @Resource(name = "deviceParamCache")
    private LoadingCache<Integer, List<AppDeviceParamDTO>> deviceParamCache;

    @Override
    @Async
    public void onApplicationEvent(DeviceOnlineEvent event) {
        try {
            Integer deviceId = event.getDeviceId();
            Integer deviceType = event.getDeviceType();
            Integer seq = event.getSeq();

            List<AppDeviceParamDTO> paramDTOList = deviceParamCache.get(deviceId);
            if (paramDTOList.size() > 0) {
                List<MachParamItem> paramList = new ArrayList<>(paramDTOList.size());
                for (AppDeviceParamDTO paramDTO : paramDTOList) {
                    MachParamItem param = null;
                    //倾斜报警参数
                    if (MsgConst.PARAM_TYPE_ROTARY == paramDTO.getParamType()) {
                        param = JSONUtil.parseObject(paramDTO.getParamValue(), MachParamRotary.class);
                    }
                    //lora appEui
                    else if (MsgConst.PARAM_TYPE_LORA_APP_EUI == paramDTO.getParamType()) {
                        param = JSONUtil.parseObject(paramDTO.getParamValue(), MachParamLoraAppEui.class);
                    }
                    //lora appKey
                    else if (MsgConst.PARAM_TYPE_LORA_APP_KEY == paramDTO.getParamType()) {
                        param = JSONUtil.parseObject(paramDTO.getParamValue(), MachParamLoraAppKey.class);
                    }
                    //阈值
                    else if (MsgConst.PARAM_TYPE_THRESHOLD == paramDTO.getParamType()) {
                        param = JSONUtil.parseObject(paramDTO.getParamValue(), MachParamThreshold.class);
                    }
                    if (param != null) {
                        paramList.add(param);
                    }
                }

                logger.info("设置硬件参数,deviceId:{},param:{}", deviceId, JSONUtil.toString(paramDTOList));
                if (paramList.size() > 0) {
                    //构造0x87
                    MachMsg0x87 resMsg = new MachMsg0x87();
                    resMsg.setStartFlag(MsgConst.START_FLAG);
                    resMsg.setDeviceType(deviceType);
                    resMsg.setDeviceId(deviceId);
                    resMsg.setSeq(seq + 1);
                    resMsg.setParamList(paramList);

                    //延迟发出数据
                    TimeUnit.SECONDS.sleep(3);

                    //响应0x87
                    Session session = sessionManager.getSessionByDeviceId(deviceId);
                    session.getChannel().writeAndFlush(resMsg).addListener(future -> {
                        logger.info("0x88发送结果,deviceId={},isDone={},isSuccess={}", deviceId, future.isDone(), future.isSuccess());
                    });
                }
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}
